package by.grsu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import by.grsu.hdm.model.ihomedevice.devices.MediaPlayer;

public class MediaPlayerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MediaPlayer mediaPlayer;
	
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		mediaPlayer = new MediaPlayer("MediaPlayer#123");
		mediaPlayer.turnOn();
		mediaPlayer.addTrack("John_Newman_-_Try");
		mediaPlayer.addTrack("Empyr_-_New_Day");
		mediaPlayer.addTrack("Prodigy_-_Girls");
		mediaPlayer.turnOff();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException
    {
        response.setContentType("text/html");
        
        PrintWriter out = response.getWriter();
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Media Player</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Media player</h3>");
        mediaPlayer.turnOn();     
        out.println("<textbox size=20/>");
        
        String playTrack = request.getParameter("playTrack");
        if(playTrack != null){
        	out.println(mediaPlayer.play(playTrack));
        }
   
        String addTrack = request.getParameter("addTrack");
        if(addTrack != null)
        {
        	out.println(mediaPlayer.addTrack(addTrack)+ "<br/>");
        }
        
        out.print("<form action=\"LoginSampleServlet\" method=POST>");
        
        out.println("Add track:");
        out.println("<input type=textbox size=20 name=addTrack>");
        out.println("<input type=submit size=20 value=Add&nbsp;Track>");
        out.println("</form>");
        
        out.print("<form action=\"LoginSampleServlet\" method=POST>");
        for(String track : mediaPlayer.getTracks()){
        	out.println("<input type=radio name=playTrack value=" + track + ">" + track + "<br/>");
        }
        out.println("<input type=submit size=20 value=Play&nbsp;Track>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    		throws IOException, ServletException
    {
        doGet(request, response);
    }

}
